<template>
  <div class="flex items-center justify-center flex-col">
    <div class="w-full mt-50">
      <BasicForm @register="registerForm">
        <template #uploadDragger>
          <!--  -->
          <a-upload-dragger
            v-model:fileList="fileList"
            name="file"
            :multiple="true"
            :custom-request="handleCustomRequest"
            :before-upload="beforeUpload"
            @change="handleUploadChange"
            @remove="handleRemove"
          >
            <p class="ant-upload-drag-icon">
              <Icon icon="ant-design:inbox-outlined" />
            </p>
            <p class="ant-upload-text">{{ t('点击或将文件拖拽到这里上传') }}</p>
            <p class="ant-upload-hint">{{ t('支持扩展名：pdf') }}</p>
          </a-upload-dragger>
        </template>
      </BasicForm>
    </div>
  </div>
</template>
<script lang="ts" setup name="ViewsSrmCwInvoiceStep1">
  import { ref, watch, inject } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { Upload } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { FileType } from 'ant-design-vue/es/upload/interface';
  import type { InvoiceApi } from '../useInvoiceApi';
  import axios from 'axios';
  //   import { emit } from 'process';
  const { t } = useI18n('srm/cw.invoice');
  const { showMessage } = useMessage();
  const emit = defineEmits(['next']);
  const invoiceApiRef = inject<import('vue').Ref<InvoiceApi>>('invoiceApi')!;
  const fileList = ref<FileType[]>([]);
  // 记录每个文件的上传取消方法
  const uploadCancelers = new Map<string, (message?: string) => void>();
  interface InvoiceParams {
    djno: string;
    pkCorp: string;
    file?: FileType;
  }

  //invoiceParams 从父组件传递过来（必须在使用前定义）
  const props = defineProps({
    invoiceParams: {
      type: Object as () => InvoiceParams,
      default: () => ({
        djno: '',
        pkCorp: '',
      }),
    },
  });

  // 仅在参数就绪时拉取，避免第一次打开参数为空的问题
  watch(
    () => [props.invoiceParams?.djno, props.invoiceParams?.pkCorp],
    async ([djno, pkCorp]) => {
      if (!djno || !pkCorp) return;
      try {
        const res: any = await invoiceApiRef.value.invoiceRecords({ djno, pkCorp });
        const list = Array.isArray(res) ? res : res?.data || [];
        fileList.value = list.map(
          (item: any) =>
            ({
              uid: String(item.id ?? item.invoiceNo ?? Math.random()),
              name: item.invoiceNo,
              status: 'done',
              invoiceRecogId: item.id,
            }) as any,
        );
      } catch (e) {
        console.error('获取发票记录失败:', e);
      }
    },
    { immediate: true },
  );
  const inputFormSchemas: FormSchema[] = [
    {
      label: t(''),
      field: 'file',
      component: 'Input',
      slot: 'uploadDragger',
      rules: [
        {
          required: true,
          validator: (_rule, _value) => {
            if (!fileList.value || fileList.value.length === 0) {
              return Promise.reject('请上传发票文件');
            }
            return Promise.resolve();
          },
        },
      ],
    },
  ];
  const [registerForm, { validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  // 上传进度在自定义上传中直接处理
  async function customSubmitFunc() {
    try {
      // 先验证表单
      await validate();

      // 检查是否有文件
      if (fileList.value.length === 0) {
        showMessage('请上传发票文件', 'warning');
        return;
      }
      emit('next');
    } catch (error) {
      console.error('上传失败:', error);
      showMessage('文件上传失败，请重试', 'error');
    }
  }

  const AUploadDragger = Upload.Dragger;
  async function handleUploadChange(info) {
    const status = info.file.status;
    if (status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (status === 'done') {
      showMessage(`${info.file.name} file uploaded successfully.`);
      // 上传完成清理取消器
      if (info.file?.uid) uploadCancelers.delete(info.file.uid);
    } else if (status === 'error') {
      showMessage(`${info.file.name} file upload failed.`, 'error');
      // 上传失败清理取消器
      if (info.file?.uid) uploadCancelers.delete(info.file.uid);
    }
    // 上传调用api puBillVouchInvoice 上传文件
  }

  // 由上传组件的 remove 事件触发真实删除
  async function handleRemove(file: any) {
    try {
      // 正在上传：中断上传并允许移除，不调用后台删除
      if (file?.status === 'uploading') {
        const cancel = uploadCancelers.get(file?.uid);
        if (cancel) {
          cancel('upload canceled by user');
          uploadCancelers.delete(file?.uid);
        }
        showMessage('已中断上传并移除文件', 'warning');
        return true;
      }

      // 上传失败：仅移除本地列表项
      if (file?.status === 'error') {
        if (file?.uid) uploadCancelers.delete(file.uid);
        showMessage('已移除上传失败的文件');
        return true;
      }

      // 已上传成功：调用后台删除接口
      const params = {
        djno: props.invoiceParams.djno,
        pkCorp: props.invoiceParams.pkCorp,
        invoiceRecogId: file?.invoiceRecogId || file?.response?.id,
      };
      const res: any = await invoiceApiRef.value.deleteInvoice(params);
      showMessage(res?.message || '删除成功');
      return true;
    } catch (err) {
      console.error('删除失败', err);
      showMessage('删除失败', 'error');
      return false;
    }
  }

  // 自定义上传请求（修正类型为 UploadRequestOption => void）
  const handleCustomRequest = (options: any): void => {
    const { file, onSuccess, onError, onProgress } = options;
    const rawFile = (file as any)?.originFileObj || (file as File);
    const uid = (file as any)?.uid;
    const source = axios.CancelToken.source();
    // 记录取消器
    if (uid) uploadCancelers.set(uid, source.cancel);

    // 构造 UploadFileParams，包含额外业务参数
    const params = {
      file: rawFile,
      djno: props.invoiceParams.djno,
      pkCorp: props.invoiceParams.pkCorp,
    };

    invoiceApiRef.value
      .uploadInvoice(
        params,
        (progressEvent: any) => {
          const percent = ((progressEvent.loaded / (progressEvent.total || 1)) * 100) | 0;
          onProgress?.({ percent });
        },
        source.token,
      )
      .then((res) => {
        console.log('上传成功:', res);
        onSuccess?.(res as any);
        if (uid) uploadCancelers.delete(uid);
        // 交由 Upload 组件通过 v-model 管理 fileList，避免重复添加
      })
      .catch((err) => {
        console.log('上传失败:', err);
        onError?.(err);
        if (uid) uploadCancelers.delete(uid);
      });
  };

  // 允许组件触发上传流程，使 customRequest 能被调用
  const beforeUpload = (_file: FileType) => {
    return true;
  };

  // 暴露给父组件调用
  defineExpose({ next: customSubmitFunc });
</script>
